#include "8259a.h"
#include "interrupt.h"
#include "printk.h"

void pic_8259a_init() {
    int i;
    for (i = 32; i < 56; ++i) {
        set_intr_gate(i, 2, g_interrupt[i - 32]);
    }
    color_printk(RED, BLACK, "8259A init\n");

    // 8259A-master ICW1~4
    io_out8(0x20, 0x11);
    io_out8(0x21, 0x20);
    io_out8(0x21, 0x04);
    io_out8(0x21, 0x01);

    // 8259A-slave ICW1~4
    io_out8(0xa0, 0x11);
    io_out8(0xa1, 0x28);
    io_out8(0xa1, 0x02);
    io_out8(0xa1, 0x01);

    // 8259A-master/slave OCW1
    io_out8(0x21, 0xfd);    // 主芯片屏蔽所有中断，除了键盘中断
    io_out8(0xa1, 0xff);    // 从芯片屏蔽所有中断

    STI();
}

// rdi传递参数regs, rsi传递参数nr
void do_irq(st_pt_regs *regs, unsigned long nr) {
    unsigned char x;
    color_printk(RED, BLACK, "do_irq:%#018lx\t", nr);
    x = io_in8(0x60);
    color_printk(RED, BLACK, "key code:%#018lx\t", x);
    io_out8(0x20, 0x20);
    color_printk(RED, BLACK, "regs:%#018lx\t<RIP:%#018lx\tRSP:%#0x18lx>\n", regs, regs->rip, regs->rsp);
}